﻿using ChuanYe.CountyFireManagement.EF.MySQL;
using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using ChuanYe.CountyFireManagement.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class TaskInfoBLL
    {
        #region 构造单例
        private TaskInfoBLL() { }
        private static TaskInfoBLL _instance;
        public static TaskInfoBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new TaskInfoBLL());
            }
        }
        #endregion

        public ResultDto<TaskMQTTResponseModel> Add(Taskinfo info)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                ResultDto<TaskMQTTResponseModel> result = new ResultDto<TaskMQTTResponseModel>();
                ef.Taskinfo.Add(info);
                ef.Entry<Taskinfo>(info).State = EntityState.Added;
                ef.SaveChanges();
                TaskMQTTResponseModel model = new TaskMQTTResponseModel();
                model.TaskId = info.TaskId;
                model.TaskName = info.TaskName;
                model.TaskType = info.TaskType;
                model.AddTime = info.AddTime;
                model.Describe = info.Describe;
                model.SendUserId = info.SendUserId;
                model.Status = info.Status;
                model.SendUserName = ef.Userinfo.Where(p => p.UserId == info.SendUserId).FirstOrDefault()?.RealName;
                model.TargetUserId =info.TargetUserId;
                result.FirstParam = model;
                return result;
            }
        }


        public ResultDto<List<TaskMQTTResponseModel>> Add(List<Taskinfo> infos)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                ResultDto<List<TaskMQTTResponseModel>> result = new ResultDto<List<TaskMQTTResponseModel>>();
                List<TaskMQTTResponseModel> list = new List<TaskMQTTResponseModel>();
                foreach (var item in infos)
                {
                    ef.Taskinfo.Add(item);
                    ef.Entry<Taskinfo>(item).State = EntityState.Added;
                    ef.SaveChanges();
                    TaskMQTTResponseModel model = new TaskMQTTResponseModel();
                    model.TaskId = item.TaskId;
                    model.TaskName = item.TaskName;
                    model.TaskType = item.TaskType;
                    model.AddTime = item.AddTime;
                    model.Describe = item.Describe;
                    model.SendUserId = item.SendUserId;
                    model.Status = item.Status;
                    model.SendUserName = ef.Userinfo.Where(p => p.UserId == item.SendUserId).FirstOrDefault()?.RealName;
                    model.TargetUserId = item.TargetUserId;
                    list.Add(model);

                }
                result.FirstParam = list;
                return result;
            }
        }




        public ResultDto<FeedbackMQTTResponseModel> Feedback(int taskId,int targetUserId, string feedbackContent, DateTime feedbackTime, List<string> imagePaths)
        {
            ResultDto<FeedbackMQTTResponseModel> result = new ResultDto<FeedbackMQTTResponseModel>();
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Taskinfo.Where(p => p.TaskId == taskId).FirstOrDefault();
                if (exist == null)
                {
                    result.Status = -1;
                    result.Message = "Taskinfo Is Not Exist";
                }
                exist.FeedbackContent = feedbackContent;
                exist.FeedbackTime = feedbackTime;
                exist.Status = 1;
                ef.Taskinfo.Add(exist);
                ef.Entry<Taskinfo>(exist).State = EntityState.Modified;
                ef.SaveChanges();
                var existImages = ef.Taskinfoimage.Where(p => p.TaskId == taskId).ToList();
                foreach (var item in existImages)
                {
                    ef.Taskinfoimage.Add(item);
                    ef.Entry<Taskinfoimage>(item).State = EntityState.Deleted;
                    ef.SaveChanges();
                }
                foreach (var item in imagePaths)
                {
                    Taskinfoimage taskinfoimage = new Taskinfoimage();
                    taskinfoimage.ImagePath = item;
                    taskinfoimage.TaskId = taskId;
                    taskinfoimage.AddTime = DateTime.Now;
                    ef.Taskinfoimage.Add(taskinfoimage);
                    ef.Entry<Taskinfoimage>(taskinfoimage).State = EntityState.Added;
                    ef.SaveChanges();
                }
                FeedbackMQTTResponseModel model = new FeedbackMQTTResponseModel();
                model.TaskId = exist.TaskId;
                model.TaskName = exist.TaskName;
                model.TaskType = exist.TaskType;
                model.Status = exist.Status;
                model.Describe = exist.Describe;
                model.SendUserId = exist.SendUserId;
                model.TargetUserId = exist.TargetUserId;
                model.TargetUserName = ef.Userinfo.Where(p => p.UserId == exist.TargetUserId).FirstOrDefault()?.RealName;
                model.FeedbackContent = feedbackContent;
                model.FeedbackTime = feedbackTime;
                result.FirstParam = model;
                return result;
            }
        }

        public int Remove(int taskId)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Taskinfo.Where(p => p.TaskId == taskId).FirstOrDefault();
                if (exist != null)
                {
                    ef.Taskinfo.Add(exist);
                    ef.Entry<Taskinfo>(exist).State = EntityState.Deleted;
                    ef.SaveChanges();

                    var existImages = ef.Taskinfoimage.Where(p => p.TaskId == exist.TaskId).ToList();
                    foreach (var item in existImages)
                    {
                        ef.Taskinfoimage.Add(item);
                        ef.Entry<Taskinfoimage>(item).State = EntityState.Deleted;
                        ef.SaveChanges();
                    }
                    return 1;
                }
                else
                {
                    return -1;
                }
            }
        }

        public ResultDto<dynamic, dynamic> GetByPage(int targetUserId,int? status,int? taskType, RequestPageBase page)
        {
            ResultDto<dynamic, dynamic> result = new ResultDto<dynamic, dynamic>();
            var sql = " select a.*,b.RealName as SendUserName,c.RealName as TargetUserName,d.DepName from  taskinfo as a ";
            sql += " left join userinfo as b on a.SendUserID=b.UserID  ";
            sql += " left join userinfo as c on a.TargetUserID=c.UserID ";
            sql += " left join department as d on a.DepID=d.DepID ";
            sql += " where 1=1 ";
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                string paramsSql = string.Empty;
                if (!string.IsNullOrEmpty(page.Keyword))
                {
                    paramsSql += $" a.TaskName like '%{page.Keyword}%'";
                    paramsSql += $" or b.RealName like '%{page.Keyword}%'";
                    paramsSql += $" or c.RealName like '%{page.Keyword}%'";
                    paramsSql = $" and ({paramsSql})";
                }
                if (status.HasValue)
                {
                    paramsSql += $" and a.`Status`='{status.Value}'"; 
                }
                if (taskType.HasValue)
                {
                    paramsSql += $" and a.`TaskType`='{taskType.Value}'";
                }
                if (targetUserId>0)
                {
                    paramsSql += $" and a.`TargetUserId`='{targetUserId}'";
                }

                var timeSql = page.TimeSql(" a.AddTime ");
                paramsSql += page.OrderByPattern == 0 ? "a.AddTime".OrderByDescending() : "a.AddTime".OrderBy();
                paramsSql += page.Limit();
                sql += timeSql;
                sql += paramsSql;
                var countSql = sql.CountSql();
                var list = ef.Database.SqlQuery<TaskInfoModel<Taskinfoimage>>(sql);

                List<int> taskIds = list.Select(s => s.TaskId).ToList();
                var taskImages=ef.Taskinfoimage.Where(p => taskIds.Contains(p.TaskId)).ToList();
                foreach (var item in list)
                {
                    item.Taskinfoimages = taskImages.Where(p => p.TaskId == item.TaskId).ToList();
                }
                result.FirstParam = list;
                result.SecondParam = ef.Database.SqlQuery(countSql).Rows[0][0];
            }
            return result;
        }
    }
}
